<template>
  <List
    item-layout="horizontal"
    :data-source="deviceFileList"
    :split="false"
    class="operation-form-modal"
  >
    <template #header>
      <Flex justify="space-between" align="center">
        <div class="text-base">
          当前路径：
          <span @click="handleJump(rootPath, true)">
            &nbsp;&nbsp;{{ rootPath }} </span
          ><span
            v-for="(item, index) in getCaption(filePath, rootPath)"
            :key="index"
            @click="handleJump(item, false)"
          >
            <RightOutlined class="mx-2" />
            {{ item }}</span
          >
        </div>
        <b-button icon="import" @click="handleBack" v-if="rootPath != filePath"
          >返回上级目录</b-button
        >
      </Flex>
    </template>
    <template #renderItem="{ item }">
      <ListItem
        @click="handleDeviceFile(item)"
        :class="{ 'stop-click': item.fileType != '1' || item.size == '0' }"
      >
        <ListItemMeta :title="getPathAndFolder(item.url)[1]">
          <template #avatar>
            <FolderOutlined
              v-if="item.fileType == 1"
              :style="{ fontSize: '30px' }"
            />
            <FileTextOutlined v-else :style="{ fontSize: '30px' }" />
          </template>
          <template #description>
            <p v-if="item.fileType == 1 && item.size != '0'">
              文件数量：{{ item.size }}
            </p>
            <p v-else-if="item.fileType == 2">
              <span class="mr-8">{{ item.date }}</span
              >{{ item.size }}
            </p>
          </template>
        </ListItemMeta>
        <template #actions v-if="item.fileType == '2'">
          <b-button icon="del" type="link" @click="getDeviceFile(item.url, '2')"
            >删除</b-button
          >
          <b-button icon="export" type="link" @click="downDeviceFile(item)"
            >下载</b-button
          >
        </template>
      </ListItem>
    </template>
  </List>
</template>

<script setup lang="tsx">
import { ref } from 'vue';
import {
  FileTextOutlined,
  FolderOutlined,
  RightOutlined,
} from '@ant-design/icons-vue';
import { Flex, List, ListItem, ListItemMeta, message } from 'ant-design-vue';
import { listToEnum } from '@/utils/utils';
import { downloadDeviceFile, operationDeviceFile } from '@/api/device';
import { getDictType } from '@/api/monitor';
import { saveRecord } from '@/api/notice';

defineOptions({
  name: 'Operation',
});

interface Props {
  pageData: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const deviceFileList: any = ref([]);
const filePath = ref('');
const rootPath = ref('');

const handleJump = (path: string, root: boolean) => {
  if (!root) {
    const endIndex = filePath.value.indexOf(path) + path.length;
    filePath.value = filePath.value.substring(0, endIndex);
  } else {
    filePath.value = path;
  }
  getDeviceFile(filePath.value, '1');
};
const getCaption = (tagStr: string, basePath: string) => {
  if (tagStr && basePath) {
    const result = tagStr.substring((basePath + '/').length);
    if (result) {
      return result.split('/');
    }
  }
};
const getPathAndFolder = (pathUrl: string) => {
  const arr = pathUrl.split('/');
  const folder = arr.splice(-1)[0];
  const path = arr.join('/');
  return [path, folder];
};
const handleBack = () => {
  const path = getPathAndFolder(filePath.value)[0];
  getDeviceFile(path, '1');
};

const handleDeviceFile = (item: any) => {
  if (item.fileType != '1' || item.size == '0') {
    return;
  }
  deviceFileList.value = [];
  getDeviceFile(item.url, '1');
};
const getDeviceFile = async (url: string, operationType: string) => {
  const code = props.pageData.code;
  if (operationType == '2') {
    await operationDeviceFile({ operationType, url, code });
    message.success('删除成功');
    getDeviceFile(filePath.value, '1');
  } else {
    const res: any = await operationDeviceFile({ operationType, url, code });
    if (!filePath.value) {
      filePath.value = getPathAndFolder(res.data[0].url)[0] || '';
      rootPath.value = filePath.value;
    } else {
      filePath.value = url;
    }
    deviceFileList.value = res.data;
  }
};
const typeEnum: any = ref();
const dictInit = () => {
  getDictType('device_operate_type').then((res) => {
    typeEnum.value = listToEnum(res.data as any, 'dictLabel', 'dictCode');
  });
};

dictInit();

const downDeviceFile = async (item: any) => {
  message.loading('文件下载中,请稍候...');
  const url = item.url;
  const code = props.pageData.code;
  await downloadDeviceFile({ url, code });
  saveRecordFn(
    props.pageData,
    { code: 200 },
    '下载',
    JSON.stringify({ url, code }),
    '/file/downloadDeviceFile',
  );
  message.destroy();
};
getDeviceFile('root', '1');

const saveRecordFn = async (
  item: any,
  res: any,
  operateButton: any,
  requestParam: any,
  operateUri: string,
) => {
  const list = [
    {
      deviceCode: item.code,
      operateModule: '设备管理/设备总览/设备文件',
      requestParam,
      status: res.code == 200 ? 1 : 0,
      operateButton,
      operateType: typeEnum.value[operateButton],
      operateUri,
    },
  ];
  await saveRecord({ list });
};
</script>
